#version 450

layout(location = 0) in vec4 fragColor;
layout(location = 1) flat in vec2 lineStart;
layout(location = 2) flat in vec2 lineEnd;
layout(location = 3) flat in float lineHalfWidth;
layout(location = 4) flat in uint lineCapType;

layout(location = 0) out vec4 outColor;

void main() {
    if (lineCapType == 1) {
        vec2 ab = lineEnd - lineStart;
        vec2 ap = gl_FragCoord.xy - lineStart;
        float projec = dot(ap, ab) / dot(ab, ab);
        projec = clamp(projec, 0.0, 1.0);
        float len = distance(lineStart, lineEnd);
        float tran = lineHalfWidth / len;
        float term = clamp(projec, tran, 1.0 - tran);
        float site = projec - term;
        tran = abs(site) * len;
        if (tran > 0.0) {
            vec2 lineDir = normalize(lineEnd - lineStart) * lineHalfWidth;
            vec2 center;
            if (site < 0) {
                center = lineStart + lineDir;
            }
            else {
                center = lineEnd - lineDir;
            }
            float dist = distance(gl_FragCoord.xy, center);
            if (dist > lineHalfWidth)
                discard;
        }
    }
    outColor = fragColor;
}